package com.example.rabbitmq.ttl;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author weiyx
 * @date 2021-01-10
 */
public class producer {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1,创建工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //2, 获取连接
        Connection connection = connectionFactory.newConnection();
        //3, 通过connection创建一个channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_ttl_exchange";
        String routingKey = "ttl.save";
        String queueName = "test_ttl_queue";

        //声明一个交换机
        channel.exchangeDeclare(exchangeName, "topic", true);
        //声明一个队列
        //队列参数
        Map<String, Object> arg = new HashMap<String, Object>(3);
        // 设置队列中消息过期时间，10秒过期（毫秒为单位）
        arg.put("x-message-ttl", 10000);
        channel.queueDeclare(queueName, true, false, false, arg);
        //建立关系
        channel.queueBind(queueName, exchangeName, routingKey);

        //5, 发送消息
        String msg = "hello rabbitmq send retuen message!";
        for (int i = 0; i < 5; i++) {
            channel.basicPublish(exchangeName, routingKey, true,null, msg.getBytes());
        }

        //单个消息也可以设置ttl.

    }



















}
